package com.example.druiddemo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.ResourceServlet;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

//@Configuration
public class DruidConfiguration {

    //单数据源
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource datasource(){
        return new DruidDataSource();
    }
    //配置监控
    //1、配置一个管理后台的servlet
    //2、配置一个监控的filter
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        Map<String, String> initMap = new HashMap<>();
        initMap.put(ResourceServlet.PARAM_NAME_USERNAME, "admin");//界面用户名
        initMap.put(ResourceServlet.PARAM_NAME_PASSWORD, "admin");//界面登录密码
        //initMap.put(ResourceServlet.PARAM_NAME_ALLOW, "localhost");//白名单
        //initMap.put(ResourceServlet.PARAM_NAME_DENY, "192.168.0.1");//黑名单
        registrationBean.setInitParameters(initMap);
        return registrationBean;
    }
    @Bean
    public FilterRegistrationBean statViewFilter(){
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        Map<String, String> initMap = new HashMap<>();
        initMap.put(WebStatFilter.PARAM_NAME_EXCLUSIONS, "*.js,*.css,/druid/*");
        bean.setInitParameters(initMap);
        bean.setUrlPatterns(Collections.singletonList("/*"));
        return bean;
    }

}
